package com.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * @author code威
 * @version 1.0
 * @description: TODO
 * @date 2021/11/28 11:35
 */
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 在这里定制请求授权规则

        //首页：所有人都可以访问，功能页：只有对应有权限人才能访问
        http.authorizeRequests().antMatchers("/").permitAll()//所有人授权
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");

        //未登录需跳转登录页   绑定前端传入参数
        http.formLogin().usernameParameter("username").passwordParameter("psd");

        //关闭网站共计   get：请求不安全   post：请求安全但需要表单请求
        //http.csrf().disable();

        //记住我定制
        http.rememberMe().rememberMeParameter("remember");
        //注销功能 跳转首页
        http.logout().logoutSuccessUrl("/");
    }


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 用户授权角色   数据库授权调用  auth.jdbcAuthentication() 方法
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()).withUser("sweetpotato")
                .password(new BCryptPasswordEncoder().encode("3272175")).roles("vip1").and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("123")).roles("vip1","vip2","vip3")
                .and().withUser("guest").password(new BCryptPasswordEncoder().encode("1573")).roles("vip3");
    }
}
